package com.example.config;

import com.example.pojo.GpsData;
import com.example.pojo.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
@ServerEndpoint("/websocket/{sbid}")
public class MyWebSocket  {

    private static Map<String , Session> onlineClientMap = new ConcurrentHashMap<>();


    @OnOpen
    public void onOpen(Session session, @PathParam("sbid") String sbid ) {
        onlineClientMap.put(sbid,session);//添加当前连接的session
        log.info("时间[{}]：与设备连接成功，当前设备[{}]",
                new Date().toLocaleString(),
                sbid,
                session.getId());
        System.out.println("连接成功");
    }


    @OnClose
    public void onClose(Session session,@PathParam("sbid") String sbid) {
        onlineClientMap.remove(sbid);//移除当前连接的session
        log.info("时间[{}]：与用户[{}]的连接关闭，当前连接编号[{}]",
                new Date().toLocaleString(),
                sbid,
                session.getId());
    }


    @OnError
    public void onError(Throwable error, Session session,@PathParam("sbid") String sbid) {
        error.printStackTrace();
    }

    @OnMessage
    public void onMsg(Session session, String message, @PathParam("sbid") String sbid) throws IOException {
        log.info("时间[{}]：来自连接编号为[{}]的消息：[{}]",
                new Date().toLocaleString(),
                session.getId(),
                message);
//        sendMessageById(sbid,"test");
    }

    public static void sendMessageById(String sbid, ResponseVo message){
        Session session = onlineClientMap.get(sbid);
        session.getAsyncRemote().sendObject(message);
    }
}

